<?php

namespace StudyBuddy;

/**
 * Class for creating
 * array of time zones
 */
class TimeZone extends \DateTimeZone {

    /**
     * Generates array suitable
     * for using it in QuickForm
     * to create drop-down menu of
     * time zones.
     *
     * @return array where keys
     * are time zone names and values
     * are strings indicating GMT offset
     * followed by timezone name.
     * This array is sorted by keys
     * (by timezone names)
     */
    public static function getSelectArray() {
        $arrResult = array();
        $arr = self::listAbbreviations();

        foreach ($arr as $abbr) {
            foreach ($abbr as $aTz) {
                $sign = ($aTz['offset'] < 0) ? '-' : (($aTz['offset'] > 0) ? '+' : '');
                $gmt = abs($aTz['offset']) / 3600;
                $hh = floor($gmt);
                $mm = $gmt - $hh;
                $mm = floor($mm * 60);
                $key = $aTz['timezone_id'];
                $val = '(GMT' . $sign . sprintf("%02s", $hh) . ':' . sprintf("%02s", $mm) . ') ' . $aTz['timezone_id'];
                if (!empty($key) && !empty($val)) {
                    $arrResult[$key] = $val;
                }
            }
        }

        ksort($arrResult);

        return $arrResult;
    }

    /**
     * Extracts value of timezone_offset from a timezone string.
     *
     * @param string $strTimezone timezone string
     * @param array $arrTimezones array of timezones
     * @return integer number of seconds, can be a negative number
     */
    public static function getTimezoneOffset($strTimezone, $arrTimezones) {
        $res = '0';
        preg_match('/\(GMT(([\-+]{1})([0-9]{2}):([0-9]{2}))\)/', $arrTimezones[$strTimezone], $matches);

        if (isset($matches[2]) && isset($matches[3]) && isset($matches[4])) {
            $intSeconds = ($matches[3] * 60 * 60) + ($matches[4] * 60);
            $prefix = ($matches[2] == '-') ? '-' : '';
            $res = trim($prefix . $intSeconds);
        }

        return (int) $res;
    }

    /**
     * Get the first available timezone name
     * that matches the offset value (in seconds)
     *
     *
     * @param $offset number of seconds from GMT
     *
     * @return first matching timezone name
     */
    public static function getTZbyoffset($intOffset) {
        $tza = \DateTimeZone::listAbbreviations();
        foreach ($tza as $abbr) {
            foreach ($abbr as $zone) {
                if ($zone['offset'] === (int) $intOffset) {
                    return $zone['timezone_id'];
                }
            }
        }

        return '';
    }

}
